const db = require('../models/database');
const crypto = require('crypto');

// 企业微信配置
const WEWORK_CONFIG = {
  corpId: process.env.WEWORK_CORP_ID,
  agentId: process.env.WEWORK_AGENT_ID,
  secret: process.env.WEWORK_SECRET
};

// 获取企业微信数据
exports.getWeworkData = async (req, res) => {
  try {
    const { script_source, hours = 24 } = req.query;
    
    // 计算时间范围
    const timeRange = parseInt(hours) * 60 * 60 * 1000; // 转换为毫秒
    const startTime = Date.now() - timeRange;
    
    let whereClause = 'WHERE timestamp > ?';
    let params = [startTime];
    
    if (script_source) {
      whereClause += ' AND script_source = ?';
      params.push(script_source);
    }
    
    // 获取事件统计
    const recentStats = await db.all(`
      SELECT 
        script_source,
        event_type, 
        COUNT(*) as count,
        MAX(timestamp) as last_occurrence,
        MIN(timestamp) as first_occurrence
      FROM events
      ${whereClause}
      GROUP BY script_source, event_type
      ORDER BY script_source, count DESC
    `, params);
    
    // 获取总体统计
    const totalStats = await db.get(`
      SELECT 
        COUNT(*) as total_events,
        COUNT(DISTINCT user_id) as unique_users,
        COUNT(DISTINCT session_id) as unique_sessions,
        COUNT(DISTINCT script_source) as script_sources
      FROM events
      ${whereClause}
    `, params);
    
    // 格式化为企业微信小工具所需的数据格式
    const formattedData = {
      title: '游戏事件统计报告',
      description: `过去${hours}小时内的事件统计` + (script_source ? ` (来源: ${script_source})` : ''),
      summary: {
        total_events: totalStats.total_events || 0,
        unique_users: totalStats.unique_users || 0,
        unique_sessions: totalStats.unique_sessions || 0,
        script_sources: totalStats.script_sources || 0
      },
      items: recentStats.map(stat => ({
        name: `[${stat.script_source}] ${stat.event_type}`,
        value: `${stat.count} 次`,
        timestamp: new Date(stat.last_occurrence).toLocaleString('zh-CN'),
        first_occurrence: new Date(stat.first_occurrence).toLocaleString('zh-CN')
      })),
      generated_at: new Date().toLocaleString('zh-CN')
    };
    
    res.status(200).json(formattedData);
  } catch (error) {
    console.error('获取企业微信数据错误:', error);
    res.status(500).json({
      success: false,
      message: '获取企业微信数据失败',
      error: error.message
    });
  }
};

// 企业微信验证回调
exports.verifyCallback = (req, res) => {
  try {
    const { msg_signature, timestamp, nonce, echostr } = req.query;
    
    // 这里应该实现企业微信的验证逻辑
    // 详见企业微信开发文档中的验证URL有效性部分
    
    if (echostr) {
      // 验证URL有效性时，直接返回echostr
      res.send(echostr);
    } else {
      res.send('success');
    }
  } catch (error) {
    console.error('企业微信验证回调错误:', error);
    res.status(500).send('error');
  }
};

// 处理企业微信消息回调
exports.handleMessage = async (req, res) => {
  try {
    // 这里处理来自企业微信的消息
    const message = req.body;
    
    // 根据消息内容返回相应的统计数据
    if (message.Content) {
      const content = message.Content.toLowerCase();
      
      if (content.includes('统计') || content.includes('stats')) {
        // 返回统计数据
        const stats = await getQuickStats();
        const response = formatStatsForWework(stats);
        
        res.json({
          msgtype: 'text',
          text: {
            content: response
          }
        });
      } else if (content.includes('帮助') || content.includes('help')) {
        // 返回帮助信息
        res.json({
          msgtype: 'text',
          text: {
            content: '可用命令：\n- 统计：查看最近24小时事件统计\n- 帮助：显示此帮助信息'
          }
        });
      } else {
        res.json({
          msgtype: 'text',
          text: {
            content: '输入"统计"查看数据，输入"帮助"查看可用命令'
          }
        });
      }
    } else {
      res.send('success');
    }
  } catch (error) {
    console.error('处理企业微信消息错误:', error);
    res.status(500).send('error');
  }
};

// 获取快速统计数据
async function getQuickStats() {
  const last24Hours = Date.now() - 24 * 60 * 60 * 1000;
  
  const stats = await db.all(`
    SELECT 
      script_source,
      COUNT(*) as count
    FROM events
    WHERE timestamp > ?
    GROUP BY script_source
    ORDER BY count DESC
  `, [last24Hours]);
  
  const total = await db.get(`
    SELECT COUNT(*) as total
    FROM events
    WHERE timestamp > ?
  `, [last24Hours]);
  
  return {
    total: total.total || 0,
    by_source: stats
  };
}

// 格式化统计数据为企业微信消息格式
function formatStatsForWework(stats) {
  let message = `📊 游戏事件统计报告\n`;
  message += `⏰ 时间：过去24小时\n`;
  message += `📈 总事件数：${stats.total}\n\n`;
  
  if (stats.by_source.length > 0) {
    message += `📋 按来源统计：\n`;
    stats.by_source.forEach(source => {
      message += `• ${source.script_source}: ${source.count}次\n`;
    });
  } else {
    message += `暂无事件数据\n`;
  }
  
  message += `\n🕐 生成时间：${new Date().toLocaleString('zh-CN')}`;
  
  return message;
}

// 发送企业微信消息（需要access_token）
exports.sendMessage = async (content, touser = '@all') => {
  try {
    // 这里需要实现获取access_token和发送消息的逻辑
    // 详见企业微信API文档
    
    console.log('发送企业微信消息:', { content, touser });
    
    // 实际实现时需要调用企业微信API
    // const accessToken = await getAccessToken();
    // const result = await sendWeworkMessage(accessToken, content, touser);
    
    return { success: true, message: '消息发送成功' };
  } catch (error) {
    console.error('发送企业微信消息错误:', error);
    return { success: false, error: error.message };
  }
};

module.exports = exports;